<?php
/**
 * Author：晴天 QQ：1186258278
 * Creation：2020/4/6 15:23
 * Filename：GoodsCart.php
 * 简单购物车操作类
 */

namespace extend;


use lib\supply\Order;
use Medoo\DB\SQL;

class GoodsCart
{

    /**
     * @param $Datas 下单参数
     * @param $GidData 商品信息
     * @param $uid 下单用户ID
     * 创建队列订单，正常下单模式
     */
    public static function OredeQueue($Datas, $GidData, $uid)
    {
        global $date, $conf;
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        if ($Datas['type'] == 1) {
            if ($Datas['mode'] == 'alipay') {
                $payment = 'alipay';
            } else if ($Datas['mode'] == 'wxpay') {
                $payment = 'wxpay';
            } else {
                $payment = 'qqpay';
            }

            if ($GidData['freight'] <> -1) {
                $freight = $DB->get_row("SELECT * FROM `sky_freight` WHERE `id` = '{$GidData['freight']}' LIMIT 1");
                if ($freight) {
                    $price = \price::freight($freight, $Datas['data'], $GidData['price'], $Datas['num']);
                } else $price = $GidData['price'] * $Datas['num'];
            } else {
                $price = $GidData['price'] * $Datas['num'];
            }

            if ($price <= 0.01 && $price <> 0) $price = 0.01;

            $price = round($price, 2);

        } else if ($Datas['type'] == 2) {
            $payment = '余额付款';

            if ($GidData['freight'] <> -1) {
                $freight = $DB->get_row("SELECT * FROM `sky_freight` WHERE `id` = '{$GidData['freight']}' LIMIT 1");
                if ($freight) {
                    $price = \price::freight($freight, $Datas['data'], $GidData['price'], $Datas['num']);
                }
            } else {
                $price = $GidData['price'] * $Datas['num'];
            }
            if ($price <= 0.01 && $price <> 0) $price = 0.01;
        } else {
            $payment = '积分兑换';
            $price = $GidData['points'] * $Datas['num'];
            if ($price <= 1 && $price <> 0) $price = 1;
        }

        if ($price == 0) {
            $payment = '免费领取';
        }

        $Data = [
            'uid' => ($uid),
            'ip' => userip(),
            'input' => json_encode($Datas['data'], JSON_UNESCAPED_UNICODE),
            'num' => $Datas['num'],
            'gid' => $Datas['gid'],
            'payment' => $payment,
            'price' => $price,
        ];

        $order = self::CartOrder($Data);

        if ($order == false) dies(-1, '订单队列创建失败，请联系管理员处理！');

        /**
         * 队列创建成功
         * 则执行付款操作！
         */

        if ($price == 0) {
            if ($uid < 1) dies('-2', '免费商品领取必须先登陆用户中心！');
            $sql = ' ( `order` = ' . $order . ' ) ';
            $re = $DB->query("UPDATE `sky_queue` SET `type`='2' ,`remark` = '当前已经免费领取了商品,系统会自动提交订单,请耐心等待！',`trade_no` = '免费领取无订单' WHERE $sql AND `payment` = '免费领取' ");
            if ($re) {
                userlog('免费领取', '您于' . $date . '领取了商品' . $GidData['name'] . ',订单号为：' . $order, $uid);
                dies(1, '领取成功,点击查看您的商品订单!');
            } else dies(-1, '领取失败,请联系管理员处理！');
        }

        switch ((int)$Datas['type']) {
            case 1:
                $json = xiaochu_en(json_encode([
                    'type' => $Datas['mode'],
                    'uid' => $uid,
                    'gid' => -2,
                    'input' => [$order],
                    'num' => 1
                ]));
                \query::OrderCookie($order);
                $urldata = is_https(false) . href() . '/other/submit.php?data=' . $json;
                dier(['code' => 2, 'msg' => '您付款成功了吗？点击下方继续!', 'url' => $urldata]);
                break;
            case 2: //余额付款
                $USERDATA = \login_data::user_data();
                if ($uid < 1) dies('-2', '请先登陆!');
                if ($USERDATA['money'] < $price) dies(-1, '当前余额不足' . $price . '元');

                $sql = ' ( `order` = ' . $order . ' ) ';
                $re = $DB->query("UPDATE `sky_queue` SET `type`='2' ,`remark` = '当前已经使用余额付款,系统会自动提交订单,请耐心等待！',`trade_no` = '余额付款无支付订单' WHERE $sql AND `payment` = '余额付款' ");

                if ($re) {
                    @$DB->query("UPDATE `sky_user` SET `money`= money-$price WHERE (`id`='{$USERDATA['id']}')");
                    userlog('余额购买', '您于' . $date . '购买了商品' . $GidData['name'] . ',付款金额为：' . $price . '元！', $USERDATA['id'], $price);
                    dies(1, '付款成功,点击查看您的商品订单!');
                } else dies(-1, '付款失败,请联系管理员处理！');
                break;
            case 3: //积分付款
                $USERDATA = \login_data::user_data();
                if ($uid < 1) dies('-2', '请先登陆!');
                if ($USERDATA['currency'] < $price) dies(-1, '当前' . $conf['currency'] . '不足' . $price . '点！');
                $sql = ' ( `order` = ' . $order . ' ) ';
                $re = $DB->query("UPDATE `sky_queue` SET `type`='2' ,`remark` = '当前已经使用" . $conf['currency'] . "兑换商品,系统会自动提交订单,请耐心等待！',`trade_no` = '积分兑换无支付订单' WHERE $sql AND `payment` = '积分兑换' ");
                if ($re) {
                    @$DB->query("UPDATE `sky_user` SET `currency`= currency-$price WHERE (`id`='{$USERDATA['id']}')");
                    userlog('积分兑换', '您于' . $date . '兑换了商品' . $GidData['name'] . ',消耗了' . $price . $conf['currency'] . '！', $USERDATA['id'], $price);
                    dies(1, '兑换成功,点击查看您的商品订单!');
                } else dies(-1, '兑换失败,请联系管理员处理！');
                break;
            default:
                dies(-1, '未知付款方式！');
                break;
        }
    }

    /**
     * @param $Data 订单信息
     * 创建订单队列！
     */
    public static function CartOrder($Data)
    {
        global $date;
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $order = date("YmdHis") . rand(11111, 99999999);
        $re = $DB->query("INSERT INTO `sky_queue` ( `type`, `order`, `uid`, `ip`, `input`, `num`, `gid`, `payment`, `price`, `remark`, `addtime`) 
VALUES ( '3', '$order', '{$Data['uid']}', '{$Data['ip']}', '{$Data['input']}', '{$Data['num']}', '{$Data['gid']}', '{$Data['payment']}', '{$Data['price']}', '待付款订单已经创建成功,请尽快完成付款，待付款订单有效期为30分钟！', '$date')");
        if ($re) {
            return $order;
        } else return false;
    }

    /**
     * @param $DataArr
     * 创建订单缓存，提交订单！
     */
    public static function CartPay($DataArr = [], $type = 1, $mode = 'alipay', $CartKey = -1)
    {
        global $times, $conf, $date;
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);

        $Array = self::CartList($DataArr, $CartKey);

        /**
         * 创建订单队列，付款后执行！
         * 返回创建好队列的订单号，若选择的是在线付款，跳转支付，若积分或余额，直接此处付款即可！
         */
        $USERDATA = \login_data::user_data();

        /**
         * 校验商品！
         */
        $arr = [];
        $text = '';
        $i = 1;
        $price = 0; //余额
        $points = 0; //积分
        $CartDet = $DataArr; //待清理购物车订单！

        if ($type == 1) {
            if ($mode == 'alipay') {
                $payment = 'alipay';
            } else if ($mode == 'wxpay') {
                $payment = 'wxpay';
            } else {
                $payment = 'qqpay';
            }
        } else if ($type == 2) {
            $payment = '余额付款';
        } else {
            $payment = '积分兑换';
        }

        foreach ($Array['data'] as $key => $v) {
            if ((int)$v['GidData']['quota'] < (int)$v['GidData']['Count']) {
                $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '当前库存不足' . $v['GidData']['Count'] . '份,当前仅剩' . $v['GidData']['quota'] . '份,无法完成结算<br>';
                unset($CartDet[$i - 1]);
                ++$i;
                continue;
            }

            if ((int)$v['num'] <= 0) {
                $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '下单数量异常,无法完成结算<br>';
                unset($CartDet[$i - 1]);
                ++$i;
                continue;
            }

            if ($v['GidData']['communityId'] == '-3') {
                $count_kami = $DB->count("SELECT count(*) FROM `sky_token` WHERE `gid` = '{$v['gid']}' AND `endtime` is null  ");
                if ($count_kami < (int)$v['GidData']['Count']) {
                    $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '卡密库存不足' . $v['GidData']['Count'] . '个,无法完成结算,当前仅剩' . $count_kami . '张卡<br>';
                    unset($CartDet[$i - 1]);
                    ++$i;
                    continue;
                }
            }

            if ($payment == '积分付款') {
                if ($USERDATA == false) {
                    $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '此商品必须登陆才可兑换哦,无法完成结算<br>';
                    unset($CartDet[$i - 1]);
                    ++$i;
                    continue;
                }

                $B = $DB->count("SELECT count(*) FROM `sky_journal` WHERE (`name` = '积分兑换' or `name` = '免费领取') AND `uid` = '{$USERDATA['id']}' AND `date` >= '$times' ");
                if (($B + $v['count']) > $conf['getinreturn']) {
                    $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '，购物车内此商品总数为：' . $v['count'] . '份！您今日最多可兑换：' . $conf['getinreturn'] . '份！,无法完成结算<br>';
                    unset($CartDet[$i - 1]);
                    ++$i;
                    continue;
                }

                $B = $DB->count("SELECT count(*) FROM `sky_journal` WHERE (`name` = '积分兑换' or `name` = '免费领取') AND `uid` = '{$USERDATA['id']}' AND `date` >= '$times' ");
                if (($B + $v['count']) > $conf['getinreturn_all']) {
                    $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '本站今日可兑换次数已经耗尽,本站今日提供的' . $conf['getinreturn_all'] . '此商品兑换次数不能满足当前商品下单总数(' . $v['GidData']['Count'] . ')！,无法完成结算<br>';
                    unset($CartDet[$i - 1]);
                    ++$i;
                    continue;
                }
                unset($B);
            }

            if ($v['GidData']['price'] == 0 || $v['GidData']['points'] == 0) {
                if ($USERDATA == false) {
                    $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '此商品必须登陆才可领取哦,无法完成结算<br>';
                    unset($CartDet[$i - 1]);
                    ++$i;
                    continue;
                }

                $B = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE  `uid` = '{$USERDATA['id']}' AND `gid`= '{$v['gid']}' AND `date` >= '$times' ");
                if ($B == null) $B = 0;

                if (($B + $v['Charge']) > (int)$conf['getinreturn']) {
                    $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '，购物车内此商品总数为：' . $v['Charge'] . '份！您今日最多可领取：' . $conf['getinreturn'] . '份！,无法完成结算<br>';
                    unset($CartDet[$i - 1]);
                    ++$i;
                    continue;
                }

                $B = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE  `gid`= '{$v['gid']}' AND `date` >= '$times' ");
                if (($B + $v['Charge']) > $conf['getinreturn_all']) {
                    $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '本站今日可领取次数已经耗尽,本站今日提供的' . $conf['getinreturn_all'] . '次商品领取次数不能满足当前商品下单总数！,无法完成结算<br>';
                    unset($CartDet[$i - 1]);
                    ++$i;
                    continue;
                }
                unset($B);
            }


            $Data = [
                'uid' => ($USERDATA == false ? '-1' : $USERDATA['id']),
                'ip' => userip(),
                'input' => json_encode($v['input'], JSON_UNESCAPED_UNICODE),
                'num' => $v['num'],
                'gid' => $v['gid'],
                'payment' => ($v['GidData']['points'] == 0 || $v['GidData']['price'] == 0 ? '免费领取' : $payment),
                'price' => ($payment == '积分兑换' ? $v['GidData']['points'] : $v['GidData']['price']),
            ];

            if ($Data['payment'] <> '免费领取') {
                //启用支付验证！
                if ($payment == '积分兑换') {

                    if ((!in_array(3, json_decode($v['GidData']['method'], TRUE)))) {
                        $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '，不支持积分兑换，无法完成结算！<br>';
                        unset($CartDet[$i - 1]);
                        ++$i;
                        continue;
                    }

                } else if ($payment == '余额付款') {

                    if ((!in_array(2, json_decode($v['GidData']['method'], TRUE)))) {
                        $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '，不支持余额购买，无法完成结算！<br>';
                        unset($CartDet[$i - 1]);
                        ++$i;
                        continue;
                    }

                } else {
                    if ((!in_array(1, json_decode($v['GidData']['method'], TRUE)))) {
                        $text .= '<font color="red">第' . $i . '件商品</font>：' . $v['GidData']['name'] . '，不支持在线付款，无法完成结算！<br>';
                        unset($CartDet[$i - 1]);
                        ++$i;
                        continue;
                    }
                }
            }

            $re = self::CartOrder($Data);

            if ($re == false) {
                $text .= '第' . $i . '件商品：' . $v['GidData']['name'] . '订单队列创建失败,无法完成结算<br>';
                unset($CartDet[$i - 1]);
                ++$i;
                continue;
            } else {
                $arr[] = $re;
            }

            $price = $price + $v['GidData']['price'];
            $points = $price + $v['GidData']['points'];
            ++$i;
        }

        if (count($arr) == 0) dies(-1, '当前无可付款商品！<br>' . $text);

        self::CartDet($CartDet, 2);

        if ($price <= 0.01 && $price <> 0) $price = 0.01;
        if ($points <= 1 && $points <> 0) $points = 1;

        if ($price == 0 || $points == 0) {
            if (\reward::user_landing() <> 1) dies('-2', '免费商品领取必须先登陆用户中心！');
            $sql = ' ( `order` = ' . implode(' OR `order` = ', $arr) . ' ) ';
            $re = $DB->query("UPDATE `sky_queue` SET `type`='2' ,`remark` = '当前已经免费领取了商品,系统会自动提交订单,请耐心等待！',`trade_no` = '免费领取无订单' WHERE $sql AND `payment` = '免费领取' ");
            if ($re) {
                foreach ($arr as $v) {
                    userlog('免费领取', '您于' . $date . '批量领取了' . count($arr) . '件商品,队列订单号为：' . $v, $USERDATA['id']);
                }
                dies(1, '领取成功,点击查看您的商品订单！<br>' . $text);
            } else dies(-1, '领取失败,请联系管理员处理！');
        }

        switch ($type) {
            case 1:
                $json = xiaochu_en(json_encode([
                    'type' => $mode,
                    'uid' => ($USERDATA == false ? '-1' : $USERDATA['id']),
                    'gid' => -2,
                    'input' => $arr,
                    'num' => 1
                ]));
                foreach ($arr as $v) {
                    \query::OrderCookie($v);
                }
                $urldata = is_https(false) . href() . '/other/submit.php?data=' . $json;

                dier(['code' => 2, 'msg' => '您付款成功了吗？点击下方继续!', 'text' => $text, 'url' => $urldata]);
                break;
            case 2: //余额付款
                if (\reward::user_landing() <> 1) dies('-2', '请先登陆!');
                if ($USERDATA['money'] < $price) dies(-1, '当前余额不足' . $price . '元');

                $sql = ' ( `order` = ' . implode(' OR `order` = ', $arr) . ' ) ';

                $re = $DB->query("UPDATE `sky_queue` SET `type`='2' ,`remark` = '当前已经使用余额付款,系统会自动提交订单,请耐心等待！',`trade_no` = '余额付款无支付订单' WHERE $sql AND `payment` = '余额付款' ");
                if ($re) {
                    @$DB->query("UPDATE `sky_user` SET `money`= money-$price WHERE (`id`='{$USERDATA['id']}')");
                    userlog('余额购买', '您于' . $date . '批量购买了' . count($arr) . '件商品,付款金额为：' . $price . '元！', $USERDATA['id'], $price);
                    dies(1, '付款成功,点击查看您的商品订单！<br>' . $text);
                } else dies(-1, '付款失败,请联系管理员处理！');
                break;
            case 3: //积分付款
                if (\reward::user_landing() <> 1) dies('-2', '请先登陆!');
                if ($USERDATA['currency'] < $points) dies(-1, '当前' . $conf['currency'] . '不足' . $points . '点！');
                $sql = ' ( `order` = ' . implode(' OR `order` = ', $arr) . ' ) ';
                $re = $DB->query("UPDATE `sky_queue` SET `type`='2' ,`remark` = '当前已经使用" . $conf['currency'] . "兑换商品,系统会自动提交订单,请耐心等待！',`trade_no` = '积分兑换无支付订单' WHERE $sql AND `payment` = '积分兑换' ");
                if ($re) {
                    @$DB->query("UPDATE `sky_user` SET `currency`= currency-$price WHERE (`id`='{$USERDATA['id']}')");
                    foreach ($arr as $v) {
                        userlog('积分兑换', '您于' . $date . '批量兑换了' . count($arr) . '件商品,累计消耗' . $conf['currency'] . $price . '个货币！，队列订单号为：' . $v, $USERDATA['id'], $price);
                    }
                    dies(1, '兑换成功,点击查看您的商品订单！<br>' . $text);
                } else dies(-1, '兑换失败,请联系管理员处理！');
                break;
            default:
                dies(-1, '未知付款方式！');
                break;
        }
    }

    /**
     * @param $Data
     * 购物车商品下单数量调整
     */
    public static function CartNum($Data)
    {
        $DB = SQL::DB();
        if ((int)$Data['num'] <= 0) dies(-1, '下单份数异常！');
        $kid = (int)$Data['id'];
        $DataCart = self::CartContent();
        $Datas = [];
        $a = 0;
        foreach (array_reverse($DataCart['data']) as $v) {
            if ($kid == $a) {
                $data_v = $v;
                $Goods = $DB->get('goods', '*', ['gid' => $v['gid'], 'state' => 1]);
                if (!$Goods) dies(-1, '商品不存在或已下架');

                $Quc = ($Goods['min'] / $Goods['quantity']);
                if ($Goods['min'] <> 0 && $Goods['min'] <> '' && $Goods['min'] <> null) {
                    if ($Data['num'] < $Quc && in_array(7, json_decode($Goods['method'], TRUE))) dies(-1, '当前商品最低购买' . $Quc . '份(' . $Goods['min'] . '个)！');
                }

                if ($Goods['max'] <> 0 && $Goods['min'] <> '' && $Goods['max'] <> null) {
                    $Quc = ($Goods['max'] / $Goods['quantity']);
                    if ($Data['num'] > $Quc && in_array(7, json_decode($Goods['method'], TRUE))) dies(-1, '当前商品最多购买' . $Quc . '份(' . $Goods['max'] . '个)！');
                }

                $price = $data_v['price'] / $data_v['num'];
                $Num = $Data['num'];
                $Pirc = round($price * $Num, 2);
                $data_v['num'] = $Num;
                $data_v['price'] = $Pirc;
                $Datas[] = $data_v;
            } else {
                $Datas[] = $v;
            }
            ++$a;
        }

        $res = self::CartAddEdit(serialize(array_reverse($Datas)), $DataCart['id']);
        if ($res == true) dies(1, '调整成功！');
        dies(-1, '调整失败！');
    }

    /**
     * 取出购物车原始数据+数据ID
     */
    public static function CartContent()
    {
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $User = \login_data::user_data();
        if ($User == false) {
            if (!empty($_COOKIE['CartKey'])) {
                if (strlen($_COOKIE['CartKey']) <> 32) dies(-1, '购物车缓存参数异常,请手动清除Cookie！');
                $CartData = $DB->get_row("SELECT * FROM `sky_cart` WHERE `cookie` = '{$_COOKIE['CartKey']}' LIMIT 1");
                if (!$CartData) return false;
            } else return false;
        } else {
            $CartData = $DB->get_row("SELECT * FROM `sky_cart` WHERE `uid` = '{$User['id']}' LIMIT 1");
            if (!$CartData) return false;
        }
        $DataArr = \config::common_unserialize($CartData['content']);

        return [
            'id' => $CartData['id'],
            'data' => $DataArr,
        ];
    }

    /**
     * @param $id
     * @param int $type
     * 移出购物车！
     */
    public static function CartDet($id, $type = 1)
    {
        $re = self::CartContent();
        if ($re == false) dies(-1, '操作失败,购物车空空如也!');
        $a = 0;
        $Data = [];

        foreach (array_reverse($re['data']) as $v) {
            if ($type == 1) {
                if ($a <> $id) {
                    $Data[] = $v;
                }
            } else {
                if (!in_array($a, $id)) {
                    $Data[] = $v;
                }
            }
            ++$a;
        }
        $res = self::CartAddEdit(serialize(array_reverse($Data)), $re['id']);
        if ($res == true) {
            if ($type == 1) {
                dies(1, '移出购物车成功！');
            } else return true;
        }

        if ($type == 1) {
            dies(1, '移出购物车失败！');
        } else return false;
    }

    /**
     * @param array $array
     * @return array
     * 取出购物车订单列表
     */
    public static function CartList($array = [], $CartKey = -1)
    {
        global $conf, $times;
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $User = \login_data::user_data();
        if ($User == false) {
            if ($CartKey <> '-1' && $CartKey <> '' && strlen($CartKey) == 32) {
                $_COOKIE['CartKey'] = $CartKey;
            }
            if (!empty($_COOKIE['CartKey'])) {
                if (strlen($_COOKIE['CartKey']) <> 32) dies(-1, '购物车缓存参数异常,请手动清除Cookie！');
                $CartData = $DB->get_row("SELECT * FROM `sky_cart` WHERE `cookie` = '{$_COOKIE['CartKey']}' LIMIT 1");
                if (!$CartData) dies(-1, '购物车空空如也');
            } else  dies(-1, '购物车空空如也');
        } else {
            $CartData = $DB->get_row("SELECT * FROM `sky_cart` WHERE `uid` = '{$User['id']}' LIMIT 1");
            if (!$CartData) dies(-1, '购物车空空如也');
        }

        $DataArr = \config::common_unserialize($CartData['content']);
        if (count($DataArr) == 0) dies(-1, '购物车空空如也');
        $DataGoods = [];
        foreach ($DataArr as $key => $v) {
            /**
             * 防止二次获取卡慢,建立函数缓存！
             */
            if ($v['num'] <= 0) $v['num'] = 1;

            $Gid = 'GID' . $v['gid']; //商品信息
            $Pid = 'Price' . $v['gid']; //价格信息
            $Count = 'Count' . $v['gid']; //同一商品下单总份数！
            $Fhuo = 'Fhuo' . $v['gid']; //发货模板信息
            if (empty($$Gid)) {
                $$Gid = $DB->get_row("SELECT * FROM `sky_goods` WHERE `gid` = '{$v['gid']}' AND `state` = '1' LIMIT 1");
                if (!$$Gid) continue;
                $pricer = \price::price_uid(\login_data::user_grade(($User == false ? -1 : $User['id'])), $$Gid['profits'], $$Gid['money'], $$Gid['custom']);
                $price = $pricer['price'];
                $points = $pricer['points'];

                $v['num'] = ((!in_array(7, json_decode($$Gid['method'], TRUE))) ? 1 : $v['num']);

                $$Count = $v['num'];
                /**
                 * 计算出剩余下单数量！
                 * quota 今日剩余库存
                 * quantity 下单数量
                 */

                if ($$Gid['freight'] <> -1) {
                    $$Fhuo = $DB->get_row("SELECT * FROM `sky_freight` WHERE `id` = '{$$Gid['freight']}' LIMIT 1");
                } else $$Fhuo = [];

                $atl = $DB->count("SELECT sum(num) FROM `sky_buylog` WHERE `gid` = '{$$Gid['gid']}' AND `date`> '$times' ");
                $$Gid['quota'] = $$Gid['quota'] - $atl;
                $$Pid = [$price, $points];
                unset($price, $points, $atl);

            } else {
                $$Gid; //商品信息
                if (!$$Gid) continue;
                $$Pid; //未计算运费和下单数量的价格
                $$Fhuo; //运费模板信息
                $v['num'] = ((!in_array(7, json_decode($$Gid['method'], TRUE))) ? 1 : $v['num']);
                $$Count = $$Count + $v['num']; //下单总份数
            }

            $Mort = $$Gid;
            $Price = $$Pid; //下单价格原始数据，1份

            $Price[1] = $Price[1] * $v['num']; //根据原始价格计算兑换价

            if ($Mort['freight'] <> -1) {
                $Price[0] = \price::freight($$Fhuo, $v['input'], $Price[0], $v['num']);
            } else {
                $Price[0] = $Price[0] * $v['num']; //根据原始价格计算售价
            }

            $v['GidData'] = [
                'name' => $Mort['name'],
                'image' => $Mort['image'],
                'price' => round($Price[0], 8),
                'points' => round($Price[1], 0),
                'cid' => $Mort['cid'],
                'count_type' => ((!in_array(7, json_decode($Mort['method'], TRUE))) ? -1 : 1),
                'min' => $Mort['min'],
                'max' => $Mort['max'],
                'quota' => $Mort['quota'],
                'quantity' => $Mort['quantity'],
                'Count' => $$Count,
                'communityId' => $Mort['sqid'],
                'method' => $Mort['method'],
            ];
            unset($Mort, $Price);
            $DataGoods[] = $v;
        }

        $DataAsrr = [];
        foreach ($DataGoods as $v) {
            $SCount = 'Count' . $v['gid'];
            $v['GidData']['Count'] = $$SCount;
            $DataAsrr[] = $v;
        }

        $Ap = 0; //免费商品总数

        if ($array <> []) {
            $DataGoods = [];

            foreach (array_reverse($DataAsrr) as $key => $value) {
                if (!in_array($key, $array)) continue;
                if ($value['GidData']['price'] == 0 || $value['GidData']['points'] == 0) {
                    ++$Ap;
                }
                $DataGoods[] = $value;
            }
            $DataAsrr = array_reverse($DataGoods);
        }

        return [
            'code' => 1,
            'msg' => '当前共有' . count($DataAsrr) . '条待付款商品!',
            'data' => array_reverse($DataAsrr),
            'count' => count($DataAsrr),
            'sitename' => $conf['sitename'],
            'Charge' => $Ap,
        ];
    }

    /**
     * @param $Data 下单商品数据
     */
    public static function CartAdd($Data)
    {
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $User = \login_data::user_data();
        $Gid = (int)$Data['gid'];
        $Goods = $DB->get_row("SELECT * FROM `sky_goods` WHERE `gid` = '$Gid' AND `state` = 1 LIMIT 1");
        if (!$Goods) dies(-1, '商品不存在！');

        if (!in_array(7, json_decode($Goods['method'], TRUE))) {
            $Data['num'] = 1;
        }

        $Goods = Order::VerifyBuy($Goods['gid'], $Data['num'], $Data['data'], ($User == false ? -1 : $User));

        $pricer = \price::price_uid(\login_data::user_grade(($User == false ? -1 : $User['id'])), $Goods['profits'], $Goods['money'], $Goods['custom']);

        if ($Goods['freight'] <> -1) {
            $freight = $DB->get_row("SELECT * FROM `sky_freight` WHERE `id` = '{$Goods['freight']}' LIMIT 1");
            if ($freight) {
                $price = \price::freight($freight, $Data['data'], $pricer['price'], $Data['num']);
            } else $price = $pricer['price'] * $Data['num'];
        } else {
            $price = $pricer['price'] * $Data['num'];
        }

        $price = round($price, 2);


        /**
         * 走cookie模式
         */
        if ($User == false) {

            if (!empty($_COOKIE['CartKey'])) {
                /**
                 * Cookie存在，必然未登录！
                 */
                if (strlen($_COOKIE['CartKey']) <> 32) dies(-1, '购物车缓存参数异常,请手动清除Cookie！');
                $GetKey = $DB->get_row("SELECT * FROM `sky_cart` WHERE `cookie` = '{$_COOKIE['CartKey']}' LIMIT 1");

                if (!$GetKey) {
                    $Key = md5(time() . userip() . rand(1000, 9999999));
                    $Content = [[
                        'gid' => (int)$Data['gid'],
                        'input' => $Data['data'],
                        'num' => $Data['num'],
                        'conts' => $Data['conts'],
                        'price' => $price,
                    ]];
                    $re = self::CartEstablish(-1, $Key, serialize($Content));
                    if ($re == true) {
                        setcookie("CartKey", $Key, time() + 3600 * 24 * 30 * 12, '/');
                        dier([
                            'code' => 1,
                            'msg' => '已经成功添加到购物车!',
                            'count' => 1,
                        ]);
                    } else dies(-1, '购物车添加失败，请联系管理员处理！');
                }
                $DataArr = \config::common_unserialize($GetKey['content']);
                $count = count($DataArr);

                if ($count == 0) {
                    $Content = [[
                        'gid' => (int)$Data['gid'],
                        'input' => $Data['data'],
                        'num' => $Data['num'],
                        'conts' => $Data['conts'],
                        'price' => $price,
                    ]];
                    $re = self::CartAddEdit(serialize($Content), $GetKey['id']);

                    if ($re == true) {
                        dier([
                            'code' => 1,
                            'msg' => '已经成功添加到购物车!',
                            'count' => 1,
                        ]);
                    } else dies(-1, '购物车添加失败，请联系管理员处理！');
                } else {
                    $DataArra = [];
                    $state = 1;
                    foreach ($DataArr as $value) {
                        /**
                         * 商品ID,下单信息一致
                         */
                        if ($value['gid'] == $Data['gid'] && $value['input'] == $Data['data'] && in_array(7, json_decode($Goods['method'], TRUE))) {
                            $state = 2;
                            $DataArra[] = [
                                'gid' => (int)$Data['gid'],
                                'input' => $Data['data'],
                                'num' => (int)$Data['num'] + (int)$value['num'],
                                'conts' => $Data['conts'],
                                'price' => (float)$price + (float)$value['price'],
                            ];
                        } else {
                            $DataArra[] = $value;
                        }
                    }

                    if ($state == 1) {
                        $Content = array_merge($DataArr, [[
                            'gid' => (int)$Data['gid'],
                            'input' => $Data['data'],
                            'num' => $Data['num'],
                            'conts' => $Data['conts'],
                            'price' => $price,
                        ]]);
                    } else {
                        $Content = $DataArra;
                    }

                }

                $re = self::CartAddEdit(serialize($Content), $GetKey['id']);
                if ($re == true) {
                    dier([
                        'code' => 1,
                        'msg' => '已经成功添加到购物车!',
                        'count' => count($Content),
                    ]);
                } else dies(-1, '购物车添加失败，请联系管理员处理！');

            } else {
                $Key = md5(time() . userip() . rand(1000, 9999999));
                $Content = [[
                    'gid' => (int)$Data['gid'],
                    'input' => $Data['data'],
                    'num' => $Data['num'],
                    'conts' => $Data['conts'],
                    'price' => $price,
                ]];
                $re = self::CartEstablish(-1, $Key, serialize($Content));
                if ($re == true) {
                    setcookie("CartKey", $Key, time() + 3600 * 24 * 30 * 12, '/');
                    dier([
                        'code' => 1,
                        'msg' => '已经成功添加到购物车!',
                        'count' => 1,
                    ]);
                } else dies(-1, '购物车添加失败，请联系管理员处理！');
            }

        } else {

            $GetUid = $DB->get_row("SELECT * FROM `sky_cart` WHERE `uid` = '{$User['id']}' LIMIT 1");
            if (!$GetUid) {
                /**
                 * 新插入
                 */
                $Content = [[
                    'gid' => (int)$Data['gid'],
                    'input' => $Data['data'],
                    'num' => $Data['num'],
                    'conts' => $Data['conts'],
                    'price' => $price,
                ]];
                $re = self::CartEstablish($User['id'], '', serialize($Content));
                if ($re == true) {
                    dier([
                        'code' => 1,
                        'msg' => '已经成功添加到购物车!',
                        'count' => 1,
                    ]);
                } else dies(-1, '购物车添加失败，请联系管理员处理！');
            } else {
                /**
                 * 写入数据
                 */
                $DataArr = \config::common_unserialize($GetUid['content']);
                $count = count($DataArr);
                if ($count == 0) {
                    $Content = [[
                        'gid' => (int)$Data['gid'],
                        'input' => $Data['data'],
                        'num' => $Data['num'],
                        'conts' => $Data['conts'],
                        'price' => $price,
                    ]];
                    $re = self::CartAddEdit(serialize($Content), $GetUid['id']);

                    if ($re == true) {
                        dier([
                            'code' => 1,
                            'msg' => '已经成功添加到购物车!',
                            'count' => 1,
                        ]);
                    } else dies(-1, '购物车添加失败，请联系管理员处理！');
                } else {
                    /**
                     * 若遇到相同的参数，则直接合并
                     */
                    $DataArra = [];
                    $state = 1;
                    foreach ($DataArr as $value) {
                        /**
                         * 商品ID,下单信息一致
                         */
                        if ($value['gid'] == $Data['gid'] && $value['input'] == $Data['data'] && in_array(7, json_decode($Goods['method'], TRUE))) {
                            $state = 2;
                            $DataArra[] = [
                                'gid' => (int)$Data['gid'],
                                'input' => $Data['data'],
                                'num' => (int)$Data['num'] + (int)$value['num'],
                                'conts' => $Data['conts'],
                                'price' => (float)$price + (float)$value['price'],
                            ];
                        } else {
                            $DataArra[] = $value;
                        }
                    }

                    if ($state == 1) {
                        $Content = array_merge($DataArr, [[
                            'gid' => (int)$Data['gid'],
                            'input' => $Data['data'],
                            'num' => $Data['num'],
                            'conts' => $Data['conts'],
                            'price' => $price,
                        ]]);
                    } else {
                        $Content = $DataArra;
                    }

                    $re = self::CartAddEdit(serialize($Content), $GetUid['id']);
                    if ($re == true) {
                        dier([
                            'code' => 1,
                            'msg' => '已经成功添加到购物车!',
                            'count' => count($Content),
                        ]);
                    } else dies(-1, '购物车添加失败，请联系管理员处理！');
                }
            }
        }
    }

    /**
     * @param string $Content
     * @param $id 购物车订单编号
     * 更新购物车数据！
     */
    public static function CartAddEdit($Content = '', $id)
    {
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $re = $DB->query("UPDATE `sky_cart` SET `content`='$Content' WHERE (`id`='$id')");
        if ($re) {
            return true;
        } else return false;
    }

    /**
     * @param int $Uid 用户ID
     * @param null $CartKey 缓存ID
     * @param array $Content 商品序列化信息！
     * 创建购物车订单,新增！
     */
    public static function CartEstablish($Uid = -1, $CartKey = null, $Content = '')
    {
        global $ip, $date;
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $re = $DB->query("INSERT INTO `sky_cart` (`uid`, `cookie`, `ip`, `content`, `addtime`) VALUES ('$Uid', '$CartKey', '$ip', '$Content', '$date')");
        if ($re) {
            return true;
        } else return false;
    }

    /**
     * 获取当前用户购物车商品数量
     */
    public static function CartCount()
    {
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        $User = \login_data::user_data();
        if ($User == false) {
            if (empty($_COOKIE['CartKey'])) {
                return 0;
            } else {
                if (strlen($_COOKIE['CartKey']) <> 32) dies(-1, '购物车缓存参数异常,请手动清除Cookie！');
                $re = $DB->get_row("SELECT * FROM `sky_cart` WHERE `cookie` = '{$_COOKIE['CartKey']}' ");
            }
        } else {
            $re = $DB->get_row("SELECT * FROM `sky_cart` WHERE `uid` = '{$User['id']}' ");
        }
        if (!$re) return 0;
        $DataArr = \config::common_unserialize($re['content']);
        return (count($DataArr) == 0 ? 0 : count($DataArr));
    }

    /**
     * @param $Uid 用户编号
     * 将未登录用户购物车的缓存数据，添加到已登陆用户中！
     */
    public static function UserCookieDer($Uid)
    {
        global $dbconfig;
        $DB = new \DB($dbconfig['host'], $dbconfig['user'], $dbconfig['pwd'], $dbconfig['dbname'], $dbconfig['port']);
        if (!empty($_COOKIE['CartKey'])) {
            $Cookey = $_COOKIE['CartKey'];
            setcookie("CartKey", null, time() - 3600 * 24 * 30 * 12, '/');
            if (strlen($Cookey) <> 32) dies(-1, '购物车缓存参数异常,请手动清除Cookie！');
            $res = $DB->get_row("SELECT * FROM `sky_cart` WHERE `cookie` = '{$Cookey}' ");
            if (!$res) return false;
            $re = $DB->get_row("SELECT * FROM `sky_cart` WHERE `uid` = '$Uid' ");
            if ($re) {
                $DataArr1 = \config::common_unserialize($res['content']);
                $DataArr2 = \config::common_unserialize($re['content']);
                $DataArr3 = array_merge($DataArr2, $DataArr1);
                self::CartAddEdit(serialize($DataArr3), $re['id']);
                $DB->query("DELETE FROM `sky_cart` WHERE (`id`='{$res['id']}')");
                return true;
            } else {
                @$DB->query("UPDATE `sky_cart` SET `uid`='$Uid',`cookie` = '' WHERE (`cookie`='$Cookey')");
                return true;
            }
        } else return false;

    }

}